package com.zhang.security;

import cn.hutool.json.JSONUtil;
import com.zhang.common.lang.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//用于拦截游客用户的增删改操作
@Component
public class GuestFilter extends OncePerRequestFilter {
    private static final String[] Forbidden_Url = {
            "/sys/user/save","/sys/user/update","/sys/user/delete","/sys/user/role/*","/sys/user/repass",
            "/sys/user/updatePass","/sys/role/save","/sys/role/update","/sys/role/delete","/sys/role/perm/*"
            ,"/sys/menu/update","/sys/menu/delete/*","/sys/menu/update"
    };

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        Object username = request.getAttribute("username");
        if(username!=null && username.equals("guest")){
            if(isForbiddenUrl(request.getRequestURI())){
                response.setContentType("application/json;charset=UTF-8");
                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.write(JSONUtil.toJsonStr(Result.fail("该用户没有此权限")).getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
                return;
            }
        }

        //往后面走
        filterChain.doFilter(request,response);
    }

    //判断访问url是否是禁止guest访问的
    private Boolean isForbiddenUrl(String url){
        Boolean is = false;
        String[] url_splits = url.split("/");

        for(String u : Forbidden_Url){
            String[] u_splits = u.split("/");
            if(url_splits.length < u_splits.length){
                is = false;
                continue;
            }
            for(int i=0;i<u_splits.length;i++){
                if(u_splits[i].equals("*")){
                    is = true;
                    break;
                }else if(u_splits[i].equals(url_splits[i])){
                    is = true;
                }else {
                    is = false;
                    break;
                }
            }
            if(is) {
                break;
            }
        }
        return is;
    }
}
